package com.myway.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myway.dao.*;
import com.myway.dto.common.JsonData;
import com.myway.dto.param.HotelParam;
import com.myway.dto.param.HouseParam;
import com.myway.dto.param.HouseTypeParam;
import com.myway.dto.param.StarDomain;
import com.myway.pojo.*;
import com.myway.service.HotelService;
import com.myway.dto.util.DateUtils;
import com.myway.dto.util.OrderNumberGenerator;
import com.myway.utils.DataGridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HotelServiceImpl implements HotelService {
    @Autowired
    private MyTabHotelMapper myTabHotelMapper;

    @Autowired
    private TabHouseMapper tabHouseMapper;

    @Autowired
    private TabOrderHotelMapper tabOrderHotelMapper;

    @Autowired
    private TabHoteDateMapper tabHoteDateMapper;

    @Autowired
    private TabHouseDateMapper tabHouseDateMapper;

//====================================hotelhome.jsp================================================

    /**
     * 热门酒店城市列表
     * @return
     */
    @Override
    public JsonData selectHotHotelCity(){
      List<TabHotel> citylist=  myTabHotelMapper.selectHotHotel();
      if(citylist.size()<=0){
          return JsonData.fail("暂无热门酒店城市");
      }
      return JsonData.success(citylist);
    }

    /**
     * 查询热门酒店
     * @param param
     * @return
     */
    @Override
    public JsonData selectHotelHomeCharact(HotelParam param) {
        List<TabHotel> list=myTabHotelMapper.selectHotHotelList(param);
        if(list.size()>0){
               return JsonData.success(list,"200");
        }else{
           return JsonData.fail("暂无数据");
        }
    }


    /**
     * 分页处理方法
     * @param param
     * @param page
     * @param rows
     * @return
     */
    @Override
    public DataGridResult selectHotelInf(HotelParam param, Integer page, Integer rows) {
       List<StarDomain> uselist = selectParamHotel(param);
        PageHelper.startPage((page+1),rows);
        param.setHotelIdList(uselist);
        List<TabHotel> list = myTabHotelMapper.selectHotel(param);
        DataGridResult result = new DataGridResult();
        result.setRows(list);
        PageInfo<TabHotel> pageInfo = new PageInfo<TabHotel>(list);
        result.setTotal(pageInfo.getTotal());

        return result;
    }

    /**
     * 获取符合预售房间的酒店的list.
     * @param param
     * @return
     */
    public  List<StarDomain>  selectParamHotel(HotelParam param){
        //所有的酒店集合
        List<TabHotel> list = myTabHotelMapper.selectHotelByAdd(param);

        //符合时间区间和目的地的酒店集合
        List<TabHoteDate> list1 = myTabHotelMapper.selectHotelDate(param);

        //定义不符合预售条件的酒店集合
        HashSet<String> set = new HashSet<>();

        if(list1.size()>0){
            for (int i=0;i<list.size();i++){
                for (int j=0;j<list1.size();j++){
                    if(list.get(i).getHotelId().equals(list1.get(j).getHotelId())){
                        if(list1.get(j).getNum()>=list.get(i).getHotelCount()){
                            set.add(list.get(i).getHotelId());
                        }
                    }

                }
            }

        }
        return  useHotelList(list, set);
    }

    /**
     *获取有用的酒店列表list
     * @param list
     * @param
     * @return
     */
    public List<StarDomain> useHotelList(List<TabHotel> list,HashSet<String> set){
        List<StarDomain> useList = new ArrayList<>();
        if(set.size()>0){
            for(int i=0; i<list.size();i++){
                for(String s : set){
                    if(!list.get(i).getHotelId().equals(s)){
                        StarDomain str= new StarDomain();
                        str.setHotelId(list.get(i).getHotelId());
                        useList.add(str);
                    }
                }

            }
        }else{
            for(int i=0; i<list.size();i++){
                StarDomain str= new StarDomain();
                str.setHotelId(list.get(i).getHotelId());
                useList.add(str);
            }
        }
        return useList;
    }
//======================================hotelDetail.jsp=======================================================

    /**
     * 酒店详情信息展示，不包含房间信息
     * @param hotelId
     * @return
     */
    @Override
    public HashMap selectHouseInf(String hotelId) {
        HashMap<String,Object> map= new HashMap<String,Object>();
        //返回酒店信息
        List<TabHotel> list =myTabHotelMapper.selectByExampleHotelId(hotelId);
        TabHotel hote = list.get(0);
        map.put("hotel",hote);
        //处理图片组，使用逗号将其隔开，返回一个String数组。
        if(hote.getHouesPicture() != null && !(hote.getHouesPicture()).equals("")){
            String picList =hote.getHouesPicture();
            String[] piczu =picList.split(",");
            map.put("piczu",piczu);
        }
        return map;
    }

    /**
     * 查询酒店某种房间是否可以预定，返回合适的房间类型集合
     * @param param
     * @return
     */
    @Override
    public JsonData selectUseHouse(HouseParam param){
        // 酒店房间类型集合
        List<HouseTypeParam> house = myTabHotelMapper.selecHouseByHotelId(param.getHotelId());
        if(house.size()<=0){
            return JsonData.fail("200");
        }

        //酒店个各种房间预售情况集合
        TabHouseDateExample example1 = new TabHouseDateExample();
        TabHouseDateExample.Criteria criteria1 =example1.createCriteria();
        criteria1.andHotelIdEqualTo(param.getHotelId());
        criteria1.andResverDateBetween(param.getStartTime(),param.getEndTime());
        List<TabHouseDate> houseDates = tabHouseDateMapper.selectByExample(example1);

        //不符合预定的酒店房间类型
        HashSet<HouseTypeParam> set = new HashSet<HouseTypeParam>();
        if(houseDates.size() > 0){
            for (int i=0;i<house.size();i++){
                for (int j=0;j<houseDates.size();j++){
                    if (house.get(i).getId()==houseDates.get(j).getHuseId()){
                        if (houseDates.get(i).getResverHousNum()>=house.get(i).getStandardNum()){
                            set.add(house.get(i));
                        }
                    }
                }

            }
        }
        //可预售的房间列表
        List<HouseTypeParam> useList =new ArrayList<>();
        //如果不符合的大于0
        if (set.size()>0){
            for (int i=0;i<house.size();i++){
                if( ! set.contains(house.get(i))){
                    useList.add(house.get(i));
                }
            }
        }else{
            useList = house;
        }
        for (int j=0;j<useList.size();j++){
            if((useList.get(j).getReserveNum()+1) >= useList.get(j).getStandardNum()){
                useList.get(j).setEnough(false);
            }else{
                useList.get(j).setEnough(true);
            }

        }
        return JsonData.success(useList);
    }

//=====================================subOrder.jsp========================================================
    /**
     * 返回酒店订单页面需要的信息
     * @param houseId
     * @return
     */
    @Override
    public Map selectReseveHouse(Integer houseId) {
       Map<String,Object> map = myTabHotelMapper.selectHotelHouse(houseId);
        return map;
    }

    /**
     * 查询房间预定数量是否在房间总数的范围内
     * @param id
     * @param num
     * @return
     */
    @Override
    public JsonData selectHouseNum(Integer id, Integer num) {
        TabHouse house =tabHouseMapper.selectByPrimaryKey(id);
        if((house.getReserveNum()+num) > house.getStandardNum()){
            return JsonData.success(500);
        }
        return JsonData.success(200);
    }

    /**
     * 插入订单信息
     * @param orderHotel
     * @return
     */
    @Override
    public JsonData addHouseOrder(TabOrderHotel orderHotel, String citySzm) {
        orderHotel.setId(OrderNumberGenerator.getOrderNo());
        orderHotel.setStatus(1);
        orderHotel.setCreateTime(new Date());
        orderHotel.setUpdateTime(new Date());
        int num = tabOrderHotelMapper.insertSelective(orderHotel);
        if(num==1){
            updateHouseInf(orderHotel.getHouseId(),orderHotel.getOrderNum());
            updateHotelDateInf(orderHotel,citySzm);
            return JsonData.success(orderHotel.getId());
        }
        return JsonData.fail("500");
    }

    /**
     * 订单成功后修改酒店各种房间预售的数量tab_house
     * @param id
     * @param resevernum
     */
    public void updateHouseInf(int id, int resevernum){
        TabHouse house = new TabHouse();
        house = tabHouseMapper.selectByPrimaryKey(id);
        house.setReserveNum((resevernum + house.getReserveNum()));
        tabHouseMapper.updateByPrimaryKeySelective(house);
    }

    /**
     * 订单成功后修改酒店总的房间数量tab_hotel
     * @param orderHotel
     * @param citySzm
     */
    public void  updateHotelDateInf( TabOrderHotel orderHotel,String citySzm){
        Date date = orderHotel.getStartTime();
        while (!date.equals(orderHotel.getEndTime())) {
            //调用修改酒店预售表的方法
            updateHotelByid(orderHotel.getHotelId(),date,orderHotel.getOrderNum(),citySzm);
            updateHouseDateById(orderHotel,date);
            date = DateUtils.addOneDay(date);
        }
    }


    /**
     * 如果根据酒店tab_hotel_date表中有改时间数据，则修改，否则插入
     * @param hotelId
     * @param date
     * @param num
     * @param city
     */
    public int updateHotelByid(String hotelId,Date date, int num,String city){
        TabHoteDateExample example = new TabHoteDateExample();
        TabHoteDateExample.Criteria criteria = example.createCriteria();
        criteria.andHotelIdEqualTo(hotelId);
        criteria.andHotelDateEqualTo(date);
        List<TabHoteDate> list =tabHoteDateMapper.selectByExample(example);
        TabHoteDate house =new TabHoteDate();
        if(list.size()>0){
            house = list.get(0);
            house.setNum(house.getNum()+num);
           return tabHoteDateMapper.updateByPrimaryKeySelective(house);
        }else{
            house.setNum(num);
            house.setHotelId(hotelId);
            house.setHotelDate(date);
            house.setCreateTime(new Date());
            house.setHotelCity(city);
            house.setUpdateTime(new Date());
            return tabHoteDateMapper.insertSelective(house);
        }
    }

    /**
     * 订单成功后修改tab_house_date表中的记录，如果当前时间有记录，则修改，无记录，则插入
     * @param orderHotel
     * @param date
     */
    public int updateHouseDateById(TabOrderHotel orderHotel,Date date){
        TabHouseDateExample example = new TabHouseDateExample();
        TabHouseDateExample.Criteria criteria =example.createCriteria();
        criteria.andHuseIdEqualTo(orderHotel.getHouseId());
        criteria.andResverDateEqualTo(date);
        List<TabHouseDate> HDlist =tabHouseDateMapper.selectByExample(example);
        TabHouseDate datahouse = new TabHouseDate();
        if(HDlist.size()>0){
            datahouse =HDlist.get(0);
            datahouse.setResverHousNum(orderHotel.getOrderNum()+datahouse.getResverHousNum());
           return tabHouseDateMapper.updateByPrimaryKeySelective(datahouse);
        }else{
            datahouse.setHotelId(orderHotel.getHotelId());
            datahouse.setHuseId(orderHotel.getHouseId());
            datahouse.setResverHousNum(orderHotel.getOrderNum());
            datahouse.setResverDate(date);
            datahouse.setCreateTime(new Date());
            datahouse.setUpdateTime(new Date());
            return tabHouseDateMapper.insertSelective(datahouse);
        }

    }
}
